package com.cyz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyz.dao.OldDao;
import com.cyz.dao.UserDao;
import com.cyz.entity.Old;
import com.cyz.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private OldDao oldDao;

    @Autowired
    private UserDao userDao;

    @RequestMapping("/uploadImage")
    public String uploadImage(MultipartFile imageFile, String account) throws IOException {
        byte[] bytes = imageFile.getBytes();
        Old old = oldDao.selectOne(new QueryWrapper<Old>().eq("name", account));
        old.setImg(bytes);
        int update = oldDao.update(old, new QueryWrapper<Old>().eq("name", account));
        return update != 0 ? "上传成功" : "上传失败";
    }

    @RequestMapping("/showImg")
    public String showImg(String account) throws IOException {
        Old old = oldDao.selectOne(new QueryWrapper<Old>().eq("id", account));
        String url = null;
        // Convert byte array to Base64 encoded string
        String base64 = Base64.getEncoder().encodeToString(old.getImg());

        // Construct the URL for the img tag with the data URI scheme
        url = "data:image/jpeg;base64," + base64;

        // Output the URL
        System.out.println(url);
        return url;
    }

    @PostMapping("/info/{account}")
    public String getInfo(@PathVariable String account){
        account = "1";
        return account;
    }

    @PostMapping("/pwd")
    public String pwd(String account, String pwd, String newPwd){
        User user = userDao.selectOne(new QueryWrapper<User>().eq("account", account).eq("pwd", pwd));
        if (user == null){
            return "密码错误";
        }
        user.setPwd(newPwd);
        int update = userDao.update(user, new QueryWrapper<User>().eq("account", account));
        return update != 0 ? "更新成功" : "更新失败";
    }
}
